﻿// See https://aka.ms/new-console-template for more information
using Hyjx.GF.Database;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Events;

try
{
    string SerilogOutputTemplate = "[{Timestamp:yyy/MM/dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {NewLine}{Exception}";
    Log.Logger = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Debug()
                                .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p =>
                                p.Level == LogEventLevel.Information).
                                WriteTo.File($"{AppDomain.CurrentDomain.BaseDirectory}/Log/{DateTime.Now:yyyyMM}/Info-.txt", rollingInterval: RollingInterval.Day,
                                rollOnFileSizeLimit: true,
                                fileSizeLimitBytes: 20_000_000,
                                retainedFileTimeLimit: TimeSpan.FromDays(90),
                                shared: true,
                                outputTemplate: SerilogOutputTemplate))
                                .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File($"{AppDomain.CurrentDomain.BaseDirectory}/Log/{DateTime.Now:yyyyMM}/Error-.txt", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true,
                                fileSizeLimitBytes: 20_000_000,
                                retainedFileTimeLimit: TimeSpan.FromDays(90),
                                shared: true,
                                outputTemplate: SerilogOutputTemplate))
                                .CreateLogger();

    string? _dbConnectionString;
    IConfigurationRoot con = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("DBsettings.json").Build();
    string? dbPath = con["GFDB:Path"];
    if (string.IsNullOrEmpty(dbPath))
    {
        Log.Error("读取数据库配置失败");
        return;
    }
    else
        _dbConnectionString = $"Filename={dbPath};Password={con["GFDB:Password"]}";

    using GFDbContext db = new(_dbConnectionString);
    DateTime clearDatetime = DateTime.Now.AddDays(-180);

    var clearDatas = db.PowderReports.Where(x => x.CreatedTime < clearDatetime).ToList();
    db.PowderReports.RemoveRange(clearDatas);
    db.SaveChanges();
    Log.Information($"已删除粉体报表在{clearDatetime}之前的{clearDatas.Count}行数据");
    Log.CloseAndFlush();
}
catch (Exception err)
{
    Log.Error($"清理粉体报表数据异常,信息:{err.Message}");
    Log.CloseAndFlush();
}
